import wx
from socket import *
import threading

class Client(wx.Frame):
    def __init__(self,name):
        # 用户身份 / 是否建立连接 / 建立连接的端口
        self.name = name.title()
        self.isConnected = False
        self.client_socket = None

        # 界面布局
        wx.Frame.__init__(self,None,title=self.name+" - 多人聊天室",size=(450,700),pos=(100,50))
        ## 面板
        self.pl = wx.Panel(self)
        ## 按钮： 加入/离开/发送信息/清空记录
        self.btn_join = wx.Button(self.pl,label="加入聊天室",pos=(10,10),size=(200,40))
        self.btn_leave = wx.Button(self.pl, label="离开聊天室", pos=(220, 10), size=(200, 40))
        self.btn_send = wx.Button(self.pl, label="发送", pos=(220, 580), size=(200, 40))
        self.btn_clear = wx.Button(self.pl, label="清空记录", pos=(10, 580), size=(200, 40))
        ## 聊天文本框
        self.text = wx.TextCtrl(self.pl,size=(400,400),pos=(10,60),style=wx.TE_READONLY|wx.TE_MULTILINE)
        ## 输入文本框
        self.input_text = wx.TextCtrl(self.pl,size=(400,100),pos=(10,470),style=wx.TE_MULTILINE)

        # 按钮事件绑定
        self.Bind(wx.EVT_BUTTON,self.ClearButton,self.btn_clear)
        self.Bind(wx.EVT_BUTTON, self.JoinButton, self.btn_join)
        self.Bind(wx.EVT_BUTTON, self.LeaveButton, self.btn_leave)
        self.Bind(wx.EVT_BUTTON, self.SendButton, self.btn_send)

    def ClearButton(self,event):
        self.input_text.Clear()

    def JoinButton(self,event):
        if self.isConnected == False:
            self.isConnected = True
            self.client_socket = socket()
            self.client_socket.connect(("127.0.0.1",8999))

            # 发送 用户名信息
            self.client_socket.send(self.name.encode("utf8"))
            # 用线程接收服务器信息
            main_thread = threading.Thread(target=self.recv_data)
            main_thread.daemon = True
            main_thread.start()

    def LeaveButton(self,event):
        self.client_socket.send("断开连接".encode("utf8"))
        self.isConnected = False

    def SendButton(self,event):
        if self.isConnected:
            text = self.input_text.GetValue()
            if text != "":
                self.client_socket.send(text.encode('utf8'))
                self.input_text.Clear()
                print("发送了奥")

    def recv_data(self):
        print(self.isConnected)
        # 有连接的清空输出信息
        while self.isConnected:
            text = self.client_socket.recv(1024).decode("utf8")
            self.text.AppendText(text+'\n')




if __name__ == "__main__":
    app = wx.App()
    # 创建窗口
    client = Client("Jack")
    # 显示窗口
    client.Show()
    app.MainLoop()